import { useUserStore } from '@/store/module/user';
import { App } from 'vue';
import * as http from "@/request/http";
import { createRouter, createWebHashHistory, Router, RouteRecordRaw } from 'vue-router';
import { ElMessage } from 'element-plus';
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: '/login'
    }, 
    {
        path: '/login',
        name: 'login',
        component: () => import("../views/Login/index.vue"),
    },
    /* {
        path: '/home',
        name: 'home',
        component: () => import("../views/Home/index.vue"),
    } */
];

export const router: Router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
    // console.log(to, from);
    let token = localStorage.getItem('token');
    const userStore = useUserStore();
    // console.log('token:', token, userStore.menus);


    // 刷新页面会出现白屏情况(没有数据, 没有token);
    // 判断: 在token为0, 数据为空时候, 请求用户信息; 在code为200时, 把请求到的数据放在pinia中;
    if (token && userStore.menus.length === 0) {
        const admindata = await http.adminInfo.adminInfo();
        if (admindata.code == 200) {
            userStore.updateMenus(admindata.data.menus);
            // 根据权限数据,添加动态路由
            const menusRoutes = userStore.getMenusRoutes;
            userStore.username = admindata.data.username; //更新用户名
            for (let k in menusRoutes) {
                // console.log("用户信息每一项k", menusRoutes[k]);
                // 一级
                let routesObjs: RouteRecordRaw = {
                    path: "/" + menusRoutes[k].name,
                    name: menusRoutes[k].name,
                    component: () => import("../views/Home/index.vue"),
                    children: []

                };
                // 二级
                menusRoutes[k].children?.forEach((citem) => {
                    routesObjs.children!.push({
                        path: citem.name,
                        name: citem.name,
                        component: () => import(`../views/${menusRoutes[k].name}/${citem.name}.vue`),
                    });
                });
                // console.log('路由菜单对象:', routesObjs);
                // 添加路由方法
                router.addRoute(routesObjs);
            }

            //动态添加首页路由对象
            router.addRoute({
                path: "/",
                component: () => import("../views/Home/index.vue"),
                children: [
                    {
                        path: "index",
                        component: () => import("../views/Index/index.vue"),
                    },
                ],
            });

            return next(to.fullPath); //动态路由，需要手动的导航。
        } else {
            localStorage.removeItem('token');
            return next('/login');
        }
    } else if (!token && to.path != '/login') {
        // console.log(123);
        return next('/login');
    } else if (token && to.path == "/login" && userStore.menus.length !== 0) {
        ElMessage.warning("请先退出登录！");
        return next(from.fullPath);
    } else {
        return next()
    }


})




// export default router;
export function initRouter(app: App<Element>) {
    app.use(router);
}

